<template>
  <div>
    <el-form :model="params" ref="ruleForm" label-width="120px" class="item" size="small">
      <el-row class="head">基本信息</el-row>
      <el-row class="body">
        <el-form-item label="商品名称" prop="name" :rules="[{required: true, message: '商品名称未填',trigger: 'blur'}]">
          <el-input v-model="params.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="副标题">
          <el-input v-model="params.subtitle" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="商品标签">
          <el-radio v-model="params.tags" label="招牌">招牌</el-radio>
          <el-radio v-model="params.tags" label="新品">新品</el-radio>
          <el-radio v-model="params.tags" label="辣">辣</el-radio>
           <el-radio v-model="params.tags" label="">无</el-radio>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input type="textarea" :rows="2" v-model="params.content" placeholder="请输入商品描述" clearable />
        </el-form-item>
        <el-form-item label="商品图片" prop="imgpath" :rules="[{required: true, message: '请上传商品图片，若已上传请忽略提示', trigger:'change'}]">
          <el-row type="flex">
            <pt-upload class="update-s" :size="0.5" :upLoadImg="params.imgpath" @getUpLoad="getUpLoad" />
            <div style="margin-left: 10px;">
              <el-button size="mini" @click="chooseImgDialog = true">在 商品库 选图片</el-button>
            </div>
          </el-row>
          <span style="margin-top: 10px;color: red;">(建议尺寸为200*200, 图片不能超过512kb, 且为jpg、png、jpeg格式)</span>
        </el-form-item>
        <el-form-item label="商品分类" prop="selltypeid" :rules="[{required: true, message: '请选择商品分类', trigger: 'change'}]">
          <el-select v-model="params.selltypeid" placeholder="请选择商品分类" clearable>
            <el-option v-for="item in classlist" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="最少购买数量" type="number" prop="minNum" :rules="[{required: true, message: '最少购买数量未填'}]">
          <el-input-number style='width: 218px'   v-model="params.minNum" :min='1' :max='100' :precision='0' />
        </el-form-item>
        <el-form-item label="是否必点"  >
          <el-radio v-model="params.required" :label="true">必点</el-radio>
          <el-radio v-model="params.required" :label="false">非必点</el-radio>
        </el-form-item>

        <el-form-item label="商品状态" prop="status" :rules="[{required: true, message: '请选择商品状态', trigger: 'change'}]">
          <el-select v-model="params.status" placeholder="请选择商品状态" clearable>
            <el-option label="正常销售" value="0" />
            <el-option label="暂停销售" value="1" />
            <el-option label="商品下架" value="2" />
          </el-select>
        </el-form-item>
      </el-row>

      <div class="head flex-row">
        <span style="width: 120px">商品规格</span>
        <span class="s-sub flex-row">
          <span style="width: 200px;">规格名称</span>
          <span style="width: 140px;">价格(元)</span>
          <span style="width: 140px;">餐盒费(元)</span>
          <span style="width: 140px;">库存(最大10000)</span>
          <span style="width: 140px;text-align: center;">开启次日置满
            <el-tooltip content="开启次日置满，则每晚过24:00自动库存回复未10000" placement="top-start">
              <el-button type="text" icon="el-icon-question"></el-button>
            </el-tooltip>
          </span>
          <div style="text-align: center;width: 100px;"></div>
        </span>
      </div>
      <el-row class="body1">
        <el-form-item v-for="(item,index) in params.standardList" :key="index" :label="'规格' + (index+1)" required  style="margin-bottom: 0">
          <el-row type="flex" justify="space-between">
            <el-form-item style="width: 200px;" :prop="'standardList.' + index + '.name'"
              :rules="[{required: true, message: '规格名称未填',trigger: 'blur'}]">
              <el-input v-model="item.name" placeholder="输入规格名称" clearable></el-input>
            </el-form-item>
            <el-form-item :prop="'standardList.' + index + '.price'" :rules="[ {required: true, message: '规格价格未填'}]">
              <el-input-number style="width: 140px;" v-model="item.price" :min='0' :max='9999' :precision='2' />
            </el-form-item>
            <el-form-item :prop="'standardList.' + index + '.packageFee'" :rules="[{required: true, message: '餐盒费未填'}]">
              <el-input-number style="width: 140px;" v-model="item.packageFee" :min='0' :max='9999' :precision='2' />
            </el-form-item>
            <el-form-item :prop="'standardList.' +index + '.num'" :rules="[{required: true, message: '库存数量未填'}]">
              <el-input-number style="width: 140px;" v-model="item.num" :min='0' :max='10000' :precision='0' />
            </el-form-item>
            <el-form-item style="text-align: center;width: 140px;">
              <el-switch v-model="item.fullNum" active-color="#409EFF" style="height: 32px; line-height: 32px" />
            </el-form-item>
            <div class="del flex-row-ver" style="width: 100px;height: 32px;" >
              <i class="el-icon-remove" style="font-size: 25px;color:#f56c6c;" v-if="index != 0" @click="delTheSpecification(index)"></i>
            </div>
          </el-row>
        </el-form-item>
        <el-button class="el-text-success" type="text"  v-if="isShow1" @click="addTheSpecification">添加规格(最多10个)</el-button>
      </el-row>
      <div class="head flex-row">
        <span style="width: 120px">商品属性</span>
        <span class="t-sub flex-row"><span class="cont">标签(可填写2-6个)</span></span>
      </div>
      <el-row class="body1">
        <el-form-item label-width="0" required  v-for="(item,index) in params.optionList" :key="index" style="margin-bottom: 0">
          <el-row type="flex" justify="space-between">
            <el-form-item :label="'属性'+ (index+1)" style="width: 380px;" :prop="'optionList.' + index + '.name'"
              :rules="[{required: true, message: '规格名称未填', trigger: 'blur'}]">
              <el-row type="flex">
                <el-input v-model="item.name" placeholder="如:温度" /><span style="margin:0 10px;">:</span>
              </el-row>
            </el-form-item>
            <el-form-item :prop="'optionList.' + index + '.sellSubOptionList'" label-width="0" style="width: 100%"
              :rules="[{ type:'array', validator:sellSubOptionList, trigger: 'change' }]">
              <el-row type="flex" justify="space-between">
                <el-input v-for="(list,subIndex) in item.sellSubOptionList" :key="subIndex"
                  style="width: 100px;margin-bottom: 0" v-model="list.name" placeholder="如:去冰" />
                <div class="del flex-row-ver" style="width: 100px;height: 32px;">
                  <i class="el-icon-remove" style="font-size: 25px;color:#f56c6c;" @click="delitiveAttribute(index)"></i>
                </div>
              </el-row>
            </el-form-item>
          </el-row>
        </el-form-item>
        <el-button class="el-text-success" type="text"  v-if="isShow2" @click="additiveAttribute()">添加属性(最多10个)</el-button>
      </el-row>
      <el-form-item>
        <el-button type="primary" :loading="issubmitLoading" @click="submitForm('ruleForm')">保存</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="选商品图片" v-dialogDrag :visible.sync="chooseImgDialog" width="900px">
      <goodsImg :name="params.name" @choseImg="getUpLoad" />
    </el-dialog>
  </div>
</template>
<script>
  import goodsImg from '@/components/dialog/goodsImgList'
  export default {
    components: { goodsImg },
    data() {
      return {
        issubmitLoading: false, // 提交等待
        isShow1: true,  // 控制添加规格按钮
        isShow2: true, // 控制添加属性按钮
        classlist: [], // 分类数据
        chooseImgDialog: false, // 选图片操作
        params: {
          businessid: this.$route.query.bid, // 商家id
          optionList: [],  //属性
          standardList: [{name: '份', id: '', price:'', packageFee:'', num: '', fullNum: true}], //规格
          name: '', // 商品名称
          unit: ' ', // 商品单位
          subtitle: '', //副标题
          tags:'', // 商品标签
          content: '',// 商品描述
          imgpath: '', // 商品图片
          minNum: 1, // 最少购买数量
          unit:' ',
          status: '0',  //商品状态
          required: false, // 是否必点
          selltypeid: '', // 商品分类
          pictureId: null
        },
      }
    },
    methods: {
      obtainCommodityClassification() { //获取商品分类数据
        const params = {businessId: this.$route.query.bid}
        this.$http.get('/server/goodsSellType/select?' + this.qs.stringify(params), {headers: {isCancel: true}}).then(res => {
          if (res.data.success) {
            this.classlist = res.data.data
          }
        })
      },
      sellSubOptionList(rule, value, callback) { //商品属性至少2个
        let count = null;
        value.forEach((item, index) => {
          if (item.name) count += 1
        })
        if (count < 2) {
          callback(new Error('至少填写两个属性标签'))
        } else {
          callback()
        }
      },
      submitForm(formName) {  //提交数据
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const params = {...this.params}
            params.optionList.forEach((item, index) => {
              let arr = []
              item.sellSubOptionList.forEach((list, sindex) => {
                if (list.name) {
                  arr.push(list)
                }
              })
              params.optionList[index].sellSubOptionList = arr
            })
            this.issubmitLoading = true
            if (this.$route.query.cid) {
              params.id = this.$route.query.cid
              this.$http.post('/server/goodsSell/update', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '商品修改成功!'})
                  this.$router.push({path: '/main/comdty/check', query: {id: this.$route.query.bid}})
                }
              }).finally(() => { this.issubmitLoading = false })
            } else {
              this.$http.post('/server/goodsSell/save', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '商品添加成功!'})
                  this.$router.push({path: '/main/comdty/check', query: {id: this.$route.query.bid}})
                }
              }).finally(() => { this.issubmitLoading = false })
            }
          } else {
            this.$message.error('有不合法的输入，请检查页面修改再提交')
            return false
          }
        });
      },
      getCommodityInformation() {//获取商品信息
        const params = {id: this.$route.query.cid}
        this.$http.get('/server/goodsSell/info?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            const row = res.data.data
            this.params.name = row.name
            this.params.content = row.content
            this.params.imgpath = row.imgpath
            this.params.selltypeid = row.selltypeid
            this.params.subtitle = row.subtitle || ''
            this.params.minNum = row.minNum||''
            this.params.unit = row.unit||'份'
            this.params.tags = row.tags ? row.tags.split(',')[0] : ''
            this.params.required = row.required
            this.params.status = row.status ? row.status.toString() : '0'
            this.params.standardList = []
            if (row.standardList.length == 0 || !row.standardList) {
              this.params.standardList = [{name: '份', id: '', price:'', packageFee:'', num: '', fullNum: true}]
            } else {
              row.standardList.forEach((item, index) => {
                this.params.standardList.push({
                  name: item.name,
                  id: item.id,
                  price: item.price||(item.price=='0'?'0':''),
                  packageFee: item.packageFee||(item.packageFee=='0'?'0':''),
                  num: item.num||(item.num=='0'?'0':''),
                  fullNum: item.fullNum
                })
              })
            }
            if (row.optionList.length == 0 || !row.optionList) {
              this.params.optionList = []
            } else {
              row.optionList.forEach((item, index) => {
                this.params.optionList.push({name: item.name, id: item.id, sellSubOptionList: []})
                item.sellSubOptionList.forEach((list, sindex) => {
                  this.params.optionList[index].sellSubOptionList.push({name: list.name, id: list.id})
                })
              })
              this.params.optionList.forEach((item, index) => {
                let length = item.sellSubOptionList.length
                if (length < 6) {
                  for (let i = 0; i < (6 - length); i++) {
                    this.params.optionList[index].sellSubOptionList.push({name: '', id: ''})
                  }
                }
              })
            }
          }
        })
      },
      addTheSpecification() {//添加规格
        this.params.standardList.push({name: '份', id: '', price:'', packageFee:'', num:'', fullNum: true})
        if (this.params.standardList.length >= 10) this.isShow1 = false
      },
      delTheSpecification(index) {//删除规格
        this.params.standardList.splice(index, 1)
        this.isShow1 = true
      },
      additiveAttribute() { //添加属性
        this.params.optionList.push({
          name: '', id: '',
          sellSubOptionList: [
            {name: '', id: ''}, {name: '', id: ''}, {name: '', id: ''}, {name: '', id: ''},
            {name: '', id: '' }, {name: '', id: ''}]
        })
        if (this.params.optionList.length >= 10) this.isShow2 = false
      },
      delitiveAttribute(index) {  //删除属性
        this.params.optionList.splice(index, 1)
        this.isShow2 = true
      },
      getUpLoad(img, id) { // 商品图片
        if (this.chooseImgDialog) this.chooseImgDialog = false
        this.params.imgpath = img
        if (id) this.params.pictureId = id
        else this.params.ptUpload = null
      },
      handleAvatarSuccess(response, file, fileList) { //获取商品图片
        this.params.imgpath = `${response.data.key}`
      },
      handleAvatarError(response, file, fileList) {
        this.$message.error('上传图片失败，请重试')
      },
      beforeAvatarUpload(file) {  ///上传验证 500K
        const isImgType = (file.type === 'image/jpeg' || file.type === 'image/png' || file.type == 'image/jpg');
        const isLt5M = (file.size / 1024 / 1024) * 2 < 1;
        if (!isImgType) {
          this.$message.error('上传图片只能是JPG/png/jpeg 格式!')
        }
        if (!isLt5M) {
          this.$message.error('上传图片大小不能超过 500kb!')
        }
        return isImgType && isLt5M
      },
    },
    mounted() {
      if (this.$route.query.bid) {
        this.obtainCommodityClassification()
        if (this.$route.query.cid) {
          this.getCommodityInformation()
        }
      } else {
        this.$router.push('/main/comdty/index')
        this.$message.error('当前页面参数丢失，已返回列表页')
      }
    }
  }
</script>
<style lang="scss" scoped>
  .item {
    max-width: 1200px;
    margin: 0 auto;
  }

  .item .head {
    height: 40px;
    line-height: 32px;
    padding: 0 15px;
    border-radius: 4px;
    justify-content: space-between;
    font-weight: bold;
    background: #eff0f5;
  }

  .item .head .t-sub {
    flex: 1;
  }

  .item .head .t-sub .cont {
    flex: 1;
  }

  .item .head .s-sub {
    flex: 1;
    justify-content: space-between;
  }

  .item .body {
    padding: 15px;
    margin-bottom: 20px;
    background: #fff;
    border: 1px solid #e2e2e2;
    border-top: none;
  }

  .update .el-upload {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .update-s {
    width: 100px!important;
    height: 100px !important;
    border: 1px dashed #e5e5e5;
  }

  .update .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }

  .item .body1 {
    padding: 15px;
    margin-bottom: 20px;
    background: #fff;
    border: 1px solid #e2e2e2;
    border-top: none;
  }

  .item .body1 .del {
    text-align: center;
    width: 100px;
    height: 40px;
    line-height: 32px
  }
</style>
